<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "6d134c3b"
    });
  daovoice('update');
  </script>




















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.1">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.1" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="日常开发测试中经常需要在数据库中造一些测试数据，为了能够快速完成任务，通常我都喜欢用Python来写。目前使用比较多的是MySQL数据库，Python有对应的很多第三方库可以用，但我还是坚持使用MySQL官方提供的支持库mysql-connector-python，因为这个库提供了MySQL的所有操作API，而且本身语法已经足够简单，对于写日常脚本来说已经足够。">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="使用Python提高工作效率之MySQL">
<meta property="og:url" content="https://www.lanshiqin.com/b4dc6b2c/index.html">
<meta property="og:site_name" content="蓝士钦">
<meta property="og:description" content="日常开发测试中经常需要在数据库中造一些测试数据，为了能够快速完成任务，通常我都喜欢用Python来写。目前使用比较多的是MySQL数据库，Python有对应的很多第三方库可以用，但我还是坚持使用MySQL官方提供的支持库mysql-connector-python，因为这个库提供了MySQL的所有操作API，而且本身语法已经足够简单，对于写日常脚本来说已经足够。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-01-30T11:44:53.286Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用Python提高工作效率之MySQL">
<meta name="twitter:description" content="日常开发测试中经常需要在数据库中造一些测试数据，为了能够快速完成任务，通常我都喜欢用Python来写。目前使用比较多的是MySQL数据库，Python有对应的很多第三方库可以用，但我还是坚持使用MySQL官方提供的支持库mysql-connector-python，因为这个库提供了MySQL的所有操作API，而且本身语法已经足够简单，对于写日常脚本来说已经足够。">



  <link rel="alternate" href="/atom.xml" title="蓝士钦" type="application/atom+xml" />




  <link rel="canonical" href="https://www.lanshiqin.com/b4dc6b2c/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>使用Python提高工作效率之MySQL | 蓝士钦</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

  <script src="/js/src/photoswipe.js?v="></script>
  <script src="/js/src/photoswipe-ui-default.js?v="></script>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蓝士钦</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">编程是一种信仰</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-相册">
    <a href="/photos/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />相册</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.lanshiqin.com/b4dc6b2c/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="蓝士钦">
      <meta itemprop="description" content="编程是一种信仰">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蓝士钦">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用Python提高工作效率之MySQL
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-01-12 11:27:48" itemprop="dateCreated datePublished" datetime="2019-01-12T11:27:48+08:00">2019-01-12</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-01-30 19:44:53" itemprop="dateModified" datetime="2019-01-30T19:44:53+08:00">2019-01-30</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>日常开发测试中经常需要在数据库中造一些测试数据，为了能够快速完成任务，通常我都喜欢用Python来写。目前使用比较多的是MySQL数据库，Python有对应的很多第三方库可以用，但我还是坚持使用MySQL官方提供的支持库<code>mysql-connector-python</code>，因为这个库提供了MySQL的所有操作API，而且本身语法已经足够简单，对于写日常脚本来说已经足够。</p>
<a id="more"></a>
<h1 id="准备工作"><a href="#准备工作" class="headerlink" title="准备工作"></a>准备工作</h1><ul>
<li>Python3.x环境</li>
<li>MySQL 8.0数据库</li>
<li>MySQL官方提供的Python驱动</li>
</ul>
<p>不同的操作系统可选的安装方式都差不多，具体内容可以参照MySQL官方文档<br><a href="https://dev.mysql.com/doc/connector-python/en/connector-python-installation-binary.html" target="_blank" rel="noopener">https://dev.mysql.com/doc/connector-python/en/connector-python-installation-binary.html</a></p>
<p>不过也不一定非要把驱动安装到系统上，比如下载驱动库就可以直接用Python去操作了，可以直接在当前的Python工程Env环境下安装<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install mysql-connector-python</span><br></pre></td></tr></table></figure></p>
<h1 id="快速使用"><a href="#快速使用" class="headerlink" title="快速使用"></a>快速使用</h1><h2 id="连接到数据库"><a href="#连接到数据库" class="headerlink" title="连接到数据库"></a>连接到数据库</h2><p>1.引入驱动库<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br></pre></td></tr></table></figure></p>
<p>2.打开/关闭连接<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">cnx = mysql.connector.connect(user=<span class="string">'root'</span>, password=<span class="string">'123456'</span>,</span><br><span class="line">                              host=<span class="string">'127.0.0.1'</span>,</span><br><span class="line">                              port=<span class="string">'3306'</span>,</span><br><span class="line">                              database=<span class="string">'py_example'</span>)</span><br><span class="line">cnx.close()</span><br></pre></td></tr></table></figure></p>
<p><code>mysql.connector.connect()</code>方法提供了很多参数，有些参数是可选的，比如端口号如果不传默认就是<code>3306</code><br>3.异常的捕获<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    cnx = mysql.connector.connect(user=<span class="string">'root'</span>, password=<span class="string">'123456'</span>,</span><br><span class="line">                                  host=<span class="string">'127.0.0.1'</span>,</span><br><span class="line">                                  port=<span class="string">'3307'</span>,</span><br><span class="line">                                  database=<span class="string">'py_example'</span>)</span><br><span class="line">    cnx.close()</span><br><span class="line"><span class="keyword">except</span> mysql.connector.Error <span class="keyword">as</span> err:</span><br><span class="line">    print(err)</span><br></pre></td></tr></table></figure></p>
<p>所连接的MySQL端口号为<code>3306</code>，在代码中故意将端口号设置为<code>3307</code>,使其无法正常连接到数据库，抛出异常后将被捕获并打印：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">2003 (HY000): Can&apos;t connect to MySQL server on &apos;127.0.0.1&apos; (61)</span><br></pre></td></tr></table></figure></p>
<p>如果要根据不同的错误码进行自定义输出，可以在头部引入<code>from mysql.connector import errorcode</code>,通过对比捕获的err.errno和errorcode的各种预定义错误值进行比对,更多连接方式和详细的异常捕获输出，可以参照官方文档：<br><a href="https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html" target="_blank" rel="noopener">https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html</a></p>
<h2 id="灵活的连接参数"><a href="#灵活的连接参数" class="headerlink" title="灵活的连接参数"></a>灵活的连接参数</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"></span><br><span class="line">config = &#123;</span><br><span class="line">    <span class="string">"user"</span>: <span class="string">"root"</span>,</span><br><span class="line">    <span class="string">"password"</span>: <span class="string">"123456"</span>,</span><br><span class="line">    <span class="string">"host"</span>: <span class="string">"127.0.0.1"</span>,</span><br><span class="line">    <span class="string">"database"</span>: <span class="string">"py_example"</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">connect</span><span class="params">(conf)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        cnx = mysql.connector.connect(**conf)</span><br><span class="line">    <span class="keyword">except</span> mysql.connector.Error <span class="keyword">as</span> err:</span><br><span class="line">        print(err)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> cnx</span><br></pre></td></tr></table></figure>
<p><code>mysql.connector.connect()</code>方法支持传入一个json对象，这样就可以很方便的把数据库连接定义到外部或者外部文件。<br>连接数据库是为了得到连接对象，所以定义一个<code>connect()</code>方法，传入参数为数据库配置，该方法返回一个数据库连接对象cnx。</p>
<h2 id="数据库的基本操作"><a href="#数据库的基本操作" class="headerlink" title="数据库的基本操作"></a>数据库的基本操作</h2><p>通过<code>mysql.connector.connect()</code>返回一个connect连接对象，通过该连接对象的<code>cursor()</code>方法可以得到操作数据库的游标。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    conn = connect(config)</span><br><span class="line">    cursor = conn.cursor()</span><br></pre></td></tr></table></figure></p>
<p>通过<code>cursor.execute()</code>方法就可以执行SQL语句了。</p>
<h3 id="创建数据库"><a href="#创建数据库" class="headerlink" title="创建数据库"></a>创建数据库</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cursor.execute(<span class="string">"CREATE DATABASE &#123;&#125; DEFAULT CHARACTER SET 'utf8mb4'"</span>.format(<span class="string">'db_name'</span>))</span><br></pre></td></tr></table></figure>
<h3 id="创建表"><a href="#创建表" class="headerlink" title="创建表"></a>创建表</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">table_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">CREATE TABLE `table_name` (</span></span><br><span class="line"><span class="string">  `t_id` INT(11) NOT NULL AUTO_INCREMENT,</span></span><br><span class="line"><span class="string">  `name` VARCHAR(255) NOT NULL ,</span></span><br><span class="line"><span class="string">  `gender` ENUM('M','F') NOT NULL ,</span></span><br><span class="line"><span class="string">  `birth_date` DATE NOT NULL,</span></span><br><span class="line"><span class="string">  PRIMARY KEY (`t_id`)</span></span><br><span class="line"><span class="string">) ENGINE = INNODB</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line">cursor.execute(table_sql)</span><br></pre></td></tr></table></figure>
<h3 id="插入数据"><a href="#插入数据" class="headerlink" title="插入数据"></a>插入数据</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">insert_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">INSERT INTO `table_name` (`name`,`gender`,`birth_date`) VALUES ('蓝士钦','M','1995-01-29')</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line">cursor.execute(insert_sql)</span><br><span class="line"><span class="comment"># conn默认不会自动提交事务，所以这里一定要手动提交事务，否则记录不会插入到MySQL中</span></span><br><span class="line">conn.commit()</span><br></pre></td></tr></table></figure>
<p>除了使用SQL拼接方式，还可以使用模块符代替，然后通过传入一个Python元组的方式<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">insert_sql_template = <span class="string">"""</span></span><br><span class="line"><span class="string">INSERT INTO `table_name` (`name`,`gender`,`birth_date`) VALUES (%s,%s,%s)</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line">insert_sql_date = (<span class="string">'蓝士钦'</span>, <span class="string">'M'</span>, date(<span class="number">1995</span>, <span class="number">1</span>, <span class="number">29</span>))</span><br><span class="line">cursor.execute(insert_sql_template,insert_sql_date)</span><br><span class="line"><span class="comment"># 提交事务</span></span><br><span class="line">conn.commit()</span><br></pre></td></tr></table></figure></p>
<p>除了使用元组，还可以使用Json格式的对象作为变量填充参数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"""</span></span><br><span class="line"><span class="string">INSERT INTO `table_name` (`name`,`gender`,`birth_date`) VALUES (%(name)s,%(gender)s,%(birth_date)s)</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line"></span><br><span class="line">data = &#123;</span><br><span class="line">    <span class="string">"name"</span>: <span class="string">"测试姓名"</span>,</span><br><span class="line">    <span class="string">"gender"</span>: <span class="string">"M"</span>,</span><br><span class="line">    <span class="string">"birth_date"</span>: date(<span class="number">1995</span>, <span class="number">1</span>, <span class="number">29</span>),</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">cursor.execute(sql,data)</span><br><span class="line"><span class="comment"># 提交事务</span></span><br><span class="line">conn.commit()</span><br></pre></td></tr></table></figure></p>
<p>可以看到代码中每次使用<code>cursor.execute()</code>方法执行sql语句之后，都需要掉用连接对象<code>conn.commit()</code>方法，<br>conn默认不会自动提交事务，所以这里一定要手动提交事务，否则记录不会插入到MySQL中。<br>不过也可以根据实际使用场景，设置每次execute都自动提交事务，只需要获取到连接对象后设置<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">conn.autocommit = <span class="keyword">True</span></span><br></pre></td></tr></table></figure></p>
<h3 id="修改数据"><a href="#修改数据" class="headerlink" title="修改数据"></a>修改数据</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">modify_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">UPDATE `table_name` SET `name`='李小龙',`birth_date`='1940-11-27' WHERE `gender`='M'</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line">cursor.execute(modify_sql)</span><br><span class="line"><span class="comment"># 提交事务</span></span><br><span class="line">conn.commit()</span><br></pre></td></tr></table></figure>
<h3 id="查询数据"><a href="#查询数据" class="headerlink" title="查询数据"></a>查询数据</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">query_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">SELECT `t_id`,`name`,`gender`,`birth_date` FROM `table_name` WHERE `birth_date` BETWEEN %s and %s</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line">start_date = date(<span class="number">1990</span>, <span class="number">1</span>, <span class="number">1</span>)</span><br><span class="line">end_date = date(<span class="number">2000</span>, <span class="number">1</span>, <span class="number">1</span>)</span><br><span class="line">cursor.execute(query_sql, (start_date, end_date))</span><br><span class="line"><span class="keyword">for</span> (t_id, name, gender, birth_date) <span class="keyword">in</span> cursor:</span><br><span class="line">    print(<span class="string">"&#123;&#125;,&#123;&#125;,&#123;&#125;,&#123;&#125;"</span>.format(t_id, name, gender, birth_date))</span><br></pre></td></tr></table></figure>
<h3 id="删除数据"><a href="#删除数据" class="headerlink" title="删除数据"></a>删除数据</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">delete_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">DELETE FROM `table_name` WHERE `name` = %(name)s</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line">delete_action = &#123;</span><br><span class="line">    <span class="string">"name"</span>: <span class="string">"姓名"</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"># 执行sql</span></span><br><span class="line">cursor.execute(delete_sql, delete_action)</span><br><span class="line"><span class="comment"># 提交事务</span></span><br><span class="line">conn.commit()</span><br></pre></td></tr></table></figure>
<h1 id="完整实例"><a href="#完整实例" class="headerlink" title="完整实例"></a>完整实例</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> date</span><br><span class="line"></span><br><span class="line">config = &#123;</span><br><span class="line">    <span class="string">"user"</span>: <span class="string">"root"</span>,</span><br><span class="line">    <span class="string">"password"</span>: <span class="string">"123456"</span>,</span><br><span class="line">    <span class="string">"host"</span>: <span class="string">"127.0.0.1"</span>,</span><br><span class="line">    <span class="string">"database"</span>: <span class="string">"py_example"</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">connect</span><span class="params">(conf)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        cnx = mysql.connector.connect(**conf)</span><br><span class="line">    <span class="keyword">except</span> mysql.connector.Error <span class="keyword">as</span> err:</span><br><span class="line">        print(err)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> cnx</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">create_database</span><span class="params">(db_cursor, db_name)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        db_cursor.execute(<span class="string">"CREATE DATABASE &#123;&#125; DEFAULT CHARACTER SET 'utf8mb4'"</span>.format(db_name))</span><br><span class="line">    <span class="keyword">except</span> mysql.connector.Error <span class="keyword">as</span> err:</span><br><span class="line">        print(err.msg)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">create_tables</span><span class="params">(db_cursor, sql_str)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        db_cursor.execute(sql_str)</span><br><span class="line">    <span class="keyword">except</span> mysql.connector.Error <span class="keyword">as</span> err:</span><br><span class="line">        print(err.msg)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">execute</span><span class="params">(db_cursor, sql_str, data_obj=None)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        db_cursor.execute(sql_str, data_obj)</span><br><span class="line">    <span class="keyword">except</span> mysql.connector.Error <span class="keyword">as</span> err:</span><br><span class="line">        print(err.msg)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    <span class="comment"># 获取连接对象</span></span><br><span class="line">    conn = connect(config)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 设置自动提交事务</span></span><br><span class="line">    conn.autocommit = <span class="keyword">True</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 获取操作游标</span></span><br><span class="line">    cursor = conn.cursor()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 创建数据库</span></span><br><span class="line">    create_database(cursor, <span class="string">"db_example"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 创建表</span></span><br><span class="line">    table_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">    CREATE TABLE `table_example` (</span></span><br><span class="line"><span class="string">      `t_id` INT(11) NOT NULL AUTO_INCREMENT,</span></span><br><span class="line"><span class="string">      `name` VARCHAR(255) NOT NULL ,</span></span><br><span class="line"><span class="string">      `gender` ENUM('M','F') NOT NULL ,</span></span><br><span class="line"><span class="string">      `birth_date` DATE NOT NULL,</span></span><br><span class="line"><span class="string">      PRIMARY KEY (`t_id`)</span></span><br><span class="line"><span class="string">    ) ENGINE = INNODB</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    create_tables(cursor, table_sql)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 插入数据</span></span><br><span class="line">    insertSQL = <span class="string">"""</span></span><br><span class="line"><span class="string">    INSERT INTO `table_example` (`name`,`gender`,`birth_date`) VALUES ('蓝士钦','M','1995-01-29')</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    execute(cursor, insertSQL)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 插入数据</span></span><br><span class="line">    insert_sql_template = <span class="string">"""</span></span><br><span class="line"><span class="string">    INSERT INTO `table_example` (`name`,`gender`,`birth_date`) VALUES (%s,%s,%s)</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    insert_sql_date = (<span class="string">'测试姓名'</span>, <span class="string">'M'</span>, date(<span class="number">1996</span>, <span class="number">8</span>, <span class="number">30</span>))</span><br><span class="line">    execute(cursor, insert_sql_template, insert_sql_date)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 插入数据</span></span><br><span class="line">    sql = <span class="string">"""</span></span><br><span class="line"><span class="string">    INSERT INTO `table_example` (`name`,`gender`,`birth_date`) VALUES (%(name)s,%(gender)s,%(birth_date)s)</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line"></span><br><span class="line">    data = &#123;</span><br><span class="line">        <span class="string">"name"</span>: <span class="string">"自由女神"</span>,</span><br><span class="line">        <span class="string">"gender"</span>: <span class="string">"F"</span>,</span><br><span class="line">        <span class="string">"birth_date"</span>: date(<span class="number">1874</span>, <span class="number">1</span>, <span class="number">1</span>),</span><br><span class="line">    &#125;</span><br><span class="line">    execute(cursor, sql, data)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 修改数据</span></span><br><span class="line">    modify_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">    UPDATE `table_example` SET `name`='李小龙',`birth_date`='1940-11-27' WHERE `gender`='M'</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    execute(cursor, modify_sql)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 查询数据</span></span><br><span class="line">    query_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">    SELECT `t_id`,`name`,`gender`,`birth_date` FROM `table_example` WHERE `birth_date` BETWEEN %s and %s</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    start_date = date(<span class="number">1900</span>, <span class="number">1</span>, <span class="number">1</span>)</span><br><span class="line">    end_date = date(<span class="number">2000</span>, <span class="number">1</span>, <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        execute(cursor, query_sql, (start_date, end_date))</span><br><span class="line">        <span class="keyword">for</span> (t_id, name, gender, birth_date) <span class="keyword">in</span> cursor:</span><br><span class="line">            print(<span class="string">"&#123;&#125;,&#123;&#125;,&#123;&#125;,&#123;&#125;"</span>.format(t_id, name, gender, birth_date))</span><br><span class="line">    <span class="keyword">except</span> mysql.connector.Error <span class="keyword">as</span> err_obj:</span><br><span class="line">        print(err_obj.msg)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 删除数据</span></span><br><span class="line">    delete_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">    DELETE FROM `table_example` WHERE `name` = %(name)s</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    delete_param = &#123;</span><br><span class="line">        <span class="string">"name"</span>: <span class="string">"李小龙"</span></span><br><span class="line">    &#125;</span><br><span class="line">    execute(cursor, delete_sql, delete_param)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 关闭操作游标</span></span><br><span class="line">    cursor.close()</span><br><span class="line">    <span class="comment"># 关闭数据库连接</span></span><br><span class="line">    conn.close()</span><br></pre></td></tr></table></figure>
      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/db2a9d2b/index.html" rel="next" title="使用Python提高工作效率之Requests库">
                <i class="fa fa-chevron-left"></i> 使用Python提高工作效率之Requests库
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/983f7127/index.html" rel="prev" title="使用Python提高工作效率之Excel">
                使用Python提高工作效率之Excel <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div id="gitalk-container"></div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="蓝士钦" />
            
              <p class="site-author-name" itemprop="name">蓝士钦</p>
              <p class="site-description motion-element" itemprop="description">编程是一种信仰</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/lanshiqin" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/l18120788756" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.jianshu.com/u/082f73dac819" target="_blank" title="JianShu"><i class="fa fa-fw fa-heartbeat"></i>JianShu</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:lanshiqin@outlook.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#准备工作"><span class="nav-number">1.</span> <span class="nav-text">准备工作</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#快速使用"><span class="nav-number">2.</span> <span class="nav-text">快速使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#连接到数据库"><span class="nav-number">2.1.</span> <span class="nav-text">连接到数据库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#灵活的连接参数"><span class="nav-number">2.2.</span> <span class="nav-text">灵活的连接参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据库的基本操作"><span class="nav-number">2.3.</span> <span class="nav-text">数据库的基本操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建数据库"><span class="nav-number">2.3.1.</span> <span class="nav-text">创建数据库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建表"><span class="nav-number">2.3.2.</span> <span class="nav-text">创建表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#插入数据"><span class="nav-number">2.3.3.</span> <span class="nav-text">插入数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#修改数据"><span class="nav-number">2.3.4.</span> <span class="nav-text">修改数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询数据"><span class="nav-number">2.3.5.</span> <span class="nav-text">查询数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除数据"><span class="nav-number">2.3.6.</span> <span class="nav-text">删除数据</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#完整实例"><span class="nav-number">3.</span> <span class="nav-text">完整实例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">蓝士钦</span>

  

  
</div>










  <div class="footer-custom">闽ICP备15027850号</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
  </div>

  

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>
<script src="/js/src/photoswipe.js?v="></script>
<script src="/js/src/photoswipe-ui-default.js?v="></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  










  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: '08543e172f1359fce9c3',
          clientSecret: 'a8dd355f95e5035e0266c695e489fa991c9d28e2',
          repo: 'lanshiqin-blog',
          owner: 'lanshiqin',
          admin: ['lanshiqin'],
          id: location.pathname,
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')           
       </script>

  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
<!-- 页面点击小红心 --> 
<script type="text/javascript" src="/js/src/love.js"></script>
<!--崩溃欺骗-->
<script type="text/javascript" src="/js/src/crash_cheat.js"></script>